package com.example.media.base;

import com.example.media.vo.MyJwtInfo;
import com.example.media.vo.PageInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class BaseController<T> {
    private final ObjectMapper objectMapper;
    protected MyJwtInfo myJwtInfo;
    protected HttpServletResponse httpServletResponse;
    protected HttpServletRequest httpServletRequest;
    protected HttpSession httpSession;

    public PageRequest getPageRequest(PageInfo<T> pageInfo) {
        List<Sort.Order> orderlist = new CopyOnWriteArrayList<>();
        if (pageInfo.getOrderList() != null)
            pageInfo.getOrderList().parallelStream().forEach(order -> {
                orderlist.add(Sort.Order.by(order.getProperty()).with(order.getDirection()));
            });
        return PageRequest.of(pageInfo.getPage(), pageInfo.getSize(), Sort.by(orderlist));
    }

    @ModelAttribute
    public void http(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession httpSession) throws IOException {
        this.httpServletRequest = httpServletRequest;
        this.httpServletResponse = httpServletResponse;
        this.httpSession = httpSession;

    }

    @ModelAttribute
    public void http(@RequestHeader(name = "Authorization", required = false) String authorization) throws IOException {
        if (!StringUtils.isEmpty(authorization)) {
            String substring = authorization.substring("Bearer ".length());
            @SuppressWarnings("deprecation")
            Jwt decode = JwtHelper.decode(substring);
            String claims = decode.getClaims();
            myJwtInfo = objectMapper.readValue(claims, MyJwtInfo.class);
        }
    }
}
